package cn.com.thingo.shyintelligent.ui.activity;

import android.annotation.SuppressLint;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.th.opensdk.openapi.NotificationInfo;
import com.th.opensdk.openapi.RoomInfo;
import com.th.opensdk.openapi.THOpenSDK;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.thingo.shyintelligent.R;
import cn.com.thingo.shyintelligent.app.App;
import cn.com.thingo.shyintelligent.base.BaseActivity;
import cn.com.thingo.shyintelligent.base.contract.GatewayListContract;
import cn.com.thingo.shyintelligent.model.bean.GatewayListBean;
import cn.com.thingo.shyintelligent.presenter.GatewayListPresenter;
import cn.com.thingo.shyintelligent.ui.adapter.GatewayAdapter;
import cn.com.thingo.shyintelligent.ui.adapter.decoration.RecycleViewDivider;
import cn.com.thingo.shyintelligent.ui.receiver.THOpenReceiver;
import cn.com.thingo.shyintelligent.util.SPUtils;
import cn.com.thingo.shyintelligent.util.ToastUtil;
import cn.com.thingo.shyintelligent.widget.CommonDialogFragment;

/**
 * 我的网关
 */
public class GatewayListActivity extends BaseActivity<GatewayListPresenter> implements GatewayListContract.View,
        GatewayAdapter.OnModifyClickListener, CommonDialogFragment.CallBack,
        THOpenReceiver.CallBack {
    @BindView(R.id.toolbar_left)
    ImageView ivLeft;
    @BindView(R.id.toolbar_title)
    TextView tvTitle;
    @BindView(R.id.gateway_rv)
    RecyclerView rvList;
    @BindView(R.id.gateway_change_hint)
    View loginProgress;
    private List<GatewayListBean.DataBean> list = new ArrayList<>();
    private GatewayAdapter adapter;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    gatewayConnectFail();
                    App.getInstance().setGatewayLoginStatus(true);
                    break;
            }
        }
    };
    private THOpenReceiver receiver;
    private int currentPosition;

    @Override
    protected int getLayout() {
        return R.layout.activity_gateway_list;
    }

    @Override
    protected void initEventAndData() {
        initView();
        initReceiver();
    }

    private void initReceiver() {
        receiver = new THOpenReceiver(GatewayListActivity.this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(NotificationInfo.BROADCAST_GATEWAY_STATUS_CHANGED);
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        mPresenter.getGatewayList(SPUtils.newInstance().getString(SPUtils.LOGIN_TOKEN));
    }

    private void initView() {
        ivLeft.setImageResource(R.mipmap.back);
        tvTitle.setText(R.string.my_gateway);
        rvList.setLayoutManager(new LinearLayoutManager(mContext));
        rvList.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.gray_12)));
        adapter = new GatewayAdapter(list, mContext);
        adapter.setListener(this);
        rvList.setAdapter(adapter);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    //加载网关列表数据的回调
    @Override
    public void viewGatewayList(GatewayListBean gatewayListBean) {
        List<GatewayListBean.DataBean> data = gatewayListBean.getData();
        if (data != null && data.size() > 0) {
            list.clear();
            list.addAll(data);
            String currentGateway = SPUtils.newInstance().getString(SPUtils.GATEWAY_CURRENT);
            String currentGatewayName = SPUtils.newInstance().getString(SPUtils.GATEWAY_CURRENT_NAME);
            if (!TextUtils.isEmpty(currentGateway)) {
                for (int i = 0; i < list.size(); i++) {
                    if (TextUtils.equals(list.get(i).getNumber(), currentGateway) && TextUtils.equals(currentGatewayName, list.get(i).getTitle())) {
                        adapter.setCurrentGatewayNum(i);
                    }
                }
            }
            adapter.notifyDataSetChanged();
        }
    }

    //切换网关
    @Override
    public void onSelectClick(int position) {
        CommonDialogFragment fragment = new CommonDialogFragment(mContext, "切换网关", "确定切换网关", "确定", position);
        fragment.show(getFragmentManager(), "change_gateway");

    }

    @OnClick({R.id.toolbar_left})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_left:
                finish();
                break;
        }
    }

    //切换网关之后选择确认的回调
    @Override
    public void determine(final int position) {
        THOpenSDK.getInstance().logoutGateway();
        App.getInstance().setSelect(false);
        final GatewayListBean.DataBean dataBean = list.get(position);
        loginProgress.setVisibility(View.VISIBLE);
//        SPUtils.newInstance().put(SPUtils.GATEWAY_IS_CREATE, dataBean.getIs_creat());
        SPUtils.newInstance().put(SPUtils.GATEWAY_CURRENT, dataBean.getNumber());
        SPUtils.newInstance().put(SPUtils.GATEWAY_CURRENT_NAME, dataBean.getTitle());
        new Thread() {
            @Override
            public void run() {
                currentPosition = position;
                App.setDataBean(dataBean);
                int i = THOpenSDK.getInstance().loginGateway(dataBean.getNumber(), dataBean.getUsername(), dataBean.getPassword());
                if (i != 0) {
                    handler.sendEmptyMessage(1);
                }
            }
        }.start();
    }

    //隐藏加载弹窗
    public void hideProgress() {
        loginProgress.setVisibility(View.GONE);
    }

    public void gatewayConnectFail() {
        ToastUtil.shortShow("切换网关失败，请检查网关！");
        hideProgress();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    //网关切换成功之后的回调
    @Override
    public void callBack() {
        ToastUtil.shortShow("网关切换成功！");
        hideProgress();
        App.getInstance().setSelect(true);
        adapter.setCurrentGatewayNum(currentPosition);
        adapter.notifyDataSetChanged();
        doSome();
    }

    public void doSome() {
        List<RoomInfo> roomList = THOpenSDK.getInstance().getRoomList();
        if (roomList.isEmpty()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            doSome();
        } else {
            RoomInfo roomInfo = roomList.get(0);
            App.getInstance().setCurrentRoomInfo(roomInfo);
        }
    }

}
